<?php
ini_set('date.timezone','asia/shanghai');
define('base_path' , dirname(__FILE__));

include(base_path.'/msg.php');
include(base_path.'/config.php');


echo 'CONNECTOIN_MSG_ID='.CONNECTOIN_MSG_ID.chr(10);

$link_msg = new msg(CONNECTOIN_MSG_ID, false);
$data_msg = new msg(DATA_MSG_ID, false);
$php_s_msg = new msg(DOWN_S_MSG_ID, false);
$php_m_msg = new msg(DOWN_M_MSG_ID, false);

if($argv[1]=='del')
{
	$link_msg->remove();
	$data_msg->remove();
	$php_s_msg->remove();
	$php_m_msg->remove();
	die('Cleared');
}

/*
while(1){	
	$data = substr('An example using the optional file and line parameters, as of PHP 4.3.0',0,rand(5,20));
	echo $data.chr(10);
	$str = $link_msg->send($data, rand(1,10));
	$str = $data_msg->receive(true, $type);
	if($str)
		echo 'C response:'.$str.chr(10);
	usleep(500000);
}*/


$user = array();
$fd = 0;
$count = 0;
$recent_fd = array();
$idx = -1;

$last_fd = 0;
while(1){
	$data_flag = false;
	$data = $link_msg->receive(true, $fd);
	if( $data && $fd>0 )
	{
		$data_flag = true;
		//echo 'Link data got:';
		if($data[0]==LINK_IN_MSG)
		{
			$user[$fd] = array(false,time());
			//echo $fd .' in';
		}else if($data[0]==LINK_OUT_MSG){
			unset($user[$fd]);
			//echo $fd .' out';
		}
		//echo chr(10);
	}

	$data = $data_msg->receive(true, $fd);
	if($data)
	{
		$recent_fd[++$idx] = $fd;
		if($idx>=20) $idx = -1;
		$count++;
		if($count%100==0) echo date("Y-m-d H:i:s").'=>'.$count.'=>N d g: '.$data.chr(10);
		if($data[0]=='m')
		{
			$php_msg->send('=You whisper say: '.$data ,$last_fd);
		}else if($data[0]=='k'){
			$php_s_msg->send(substr($data,0,3).' You say: '.substr($data,3) , $fd);
		}else if($data[0]=='b'){			
			$php_s_msg->send(substr($data,0,3).' You say: '.substr($data,3) , $fd);
		}else if($data[0]=='s'){
			$php_m_msg->send('Group message: '.$data.PHP_DMSG_SPLIIER.$last_fd.PHP_DMSG_SPLIIER.$fd ,SEND_SPE_FD_VALUE);
		}else $php_s_msg->send('All say: '.$data , $fd);
		$last_fd = $fd;
		$data_flag = true;
	}
	if(!$data_flag) usleep(5000);
}
echo 'Done';

